package com.gensdai.leliang.serve;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.entity.UserNameBean;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.utils.BaseUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/23.
 */

public class ActionEnter extends Service {
    SharedPreferences share;
    SharedPreferences.Editor ed;
    UserNameBean user;
    AlertDialog isExit;
    Context mcontext;

    private String banben;// 版本号
    private String showPage;// 改版内容
    private int forceUpdate = -1;// 是否强制更新 1,为强制更新

    private final int ENTER = 1;// 登录标识
    private final int UPDATE = 2;// 更新标识
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {

                            user = (UserNameBean) new json_base().jsonEnter(new JSONObject((String) msg.obj));

                            saveInfo(user);
//                            ed.putString("user_id", user.getUid());
//                            ed.putString("token", user.getToken());
//                            ed.putBoolean("enter_state", true);
//                            ed.putString("id", user.getId());
//                            ed.putString("user_name", user.getName());
//                            ed.putString("phone", user.getPhone());
//                            ed.putBoolean("hasPayPassword", user.getHasPayPassword());
//                            ed.putString("money", user.getMoney());
//                            ed.putString("recommendUserNo", user.getInviteNumber());
//                            ed.putBoolean("enter_state", true);
//                            ed.putString("memberType", user.getMemberType());
//                            ed.putString("userno", user.getUserno());
//                            ed.putString("daifuNum", user.getDaifuNum());
//                            ed.putString("daifaNum", user.getDaifaNum());
//                            ed.putString("daishouNum", user.getDaishouNum());
//                            ed.putString("name", user.getAddress().getUser_name());
//                            ed.putString("province", user.getAddress().getCityId());
//                            ed.putString("addressId", user.getAddress().getId());
//                            ed.putString("detailAddress", user.getAddress().getAddress());
//                            ed.putString("adressPhone", user.getAddress().getPhone());

//                            ed.commit();
                        } else {
                            Toast.makeText(getApplicationContext(),
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case UPDATE:
                    if (new json_base().GOOD((String) msg.obj)) {
                        JSONObject data = null;
                        try {
                            data = new JSONObject((String) msg.obj)
                                    .getJSONObject("data");
                            banben = data.getString("version");
                            showPage = data.getString("showPage");
                            forceUpdate = data.getInt("forceUpdate");
//                            startdownload();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        LoginRequest22Str();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 调用登陆接口
     */
    private void LoginRequest22Str() {
        //获取edit的值后请求

        String name = share.getString("phone", "");
        String password = share.getString("password", "");
        if (password.equals("")) {
            Log.e("ActionEnter", "密码为空");
            return;
        }

        String resultPassword = BaseUtils.EncryptedPassword(password);
        Log.e("ActionEnter_password", resultPassword);

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("username", /*"123456"*/name);   //手机号
        loginParams.put("password", resultPassword);                  //密码
        toStr(loginParams);
        Map<String, String> updateParams = new HashMap<>();
        updateParams.put("phoneType", "android");
//        UpdatetoStr(updateParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        ApiService.getInstance(this).LoginRequest2Str(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("ActionEnter", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    //返回字符串类型
    private void UpdatetoStr(Map<String, String> loginParams) {
        ApiService.getInstance().UpdateRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("ActionEnter", s);
                        Message msg = new Message();
                        msg.what = UPDATE;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
            // return this.getString(R.string.banbenhao) + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 通过包名 在应用商店打开应用
     */
    private void openApplicationMarket() {
        try {
            String str = "market://details?id=" + "com.gensdai.leliang";
            Intent localIntent = new Intent(Intent.ACTION_VIEW);
            localIntent.setData(Uri.parse(str));
            startActivity(localIntent);
        } catch (Exception e) {
            // 打开应用商店失败 可能是没有手机没有安装应用市场
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "打开应用商店失败",
                    Toast.LENGTH_SHORT).show();
            // 调用系统浏览器进入商城
            String url = "http://app.mi.com/detail/163525?ref=search";
            openLinkBySystem(url);
        }
    }

    /**
     * 调用系统浏览器打开网页
     *
     * @param url 地址
     */
    private void openLinkBySystem(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    /**
     * 启动下载类
     */
    private void startdownload() {
        if (getVersion().equals(banben)) {
//            Toast.makeText(this, "与当前版本号一致！", Toast.LENGTH_SHORT).show();
        } else {
            // 创建退出对话框
            isExit = new AlertDialog.Builder(getApplicationContext()).create();
            // 设置对话框标题
            isExit.setTitle("正事贷提示：");
            // 设置对话框消息
            isExit.setMessage(showPage + "发现新版本，要试试嘛？！");
            // 添加选择按钮并注册监听
            isExit.setButton("确定", listener);
            isExit.setButton2("取消", listener);
            // 显示对话框
            isExit.show();
        }
    }


    /**
     * 监听对话框里面的button点击事件
     */
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    openApplicationMarket();
                    // String strUrl =
                    // "http://gdown.baidu.com/data/wisegame/55dc62995fe9ba82/jinritoutiao_448.apk";
                    // new Download().StartDownload(url, "正事贷", user_more.this,
                    // true);
                    // new Download().StartDownload(strUrl, "正事贷", user_more.this,
                    // true);
                    isExit.dismiss();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    isExit.dismiss();
                    break;
                default:
                    break;
            }
        }
    };



    public static void saveInfo(UserNameBean user){

        SharedPreferences share;
        SharedPreferences.Editor ed;

        share = AppApplication.getContext().getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();

        ed.putString("user_id", user.getUid());
        ed.putString("token", user.getToken());
        ed.putBoolean("enter_state", true);
        ed.putString("id", user.getId());
        ed.putString("user_name", user.getName());
        ed.putString("phone", user.getPhone());
        ed.putBoolean("hasPayPassword", user.getHasPayPassword());
        ed.putString("money", user.getMoney());
        ed.putString("recommendUserNo", user.getInviteNumber());
        ed.putBoolean("enter_state", true);
        ed.putString("memberType", user.getMemberType());
        ed.putString("userno", user.getUserno());
        ed.putString("daifuNum", user.getDaifuNum());
        ed.putString("daifaNum", user.getDaifaNum());
        ed.putString("daishouNum", user.getDaishouNum());
        ed.putString("name", user.getAddress().getUser_name());
        ed.putString("province", user.getAddress().getCityId());
        ed.putString("addressId", user.getAddress().getId());
        ed.putString("detailAddress", user.getAddress().getAddress());
        ed.putString("adressPhone", user.getAddress().getPhone());
        ed.putString("adressPhone", user.getAddress().getPhone());
        ed.putString("level", user.getLevel());


        //put权限 0：无权限、1：有权限
        if(user.getMappModule() != null){
            ed.putString("myWallet", user.getMappModule().myWallet);
            ed.putString("bindAlipay", user.getMappModule().bindAlipay);
            ed.putString("contactUs", user.getMappModule().contactUs);
            ed.putString("receiveAddress", user.getMappModule().receiveAddress);
            ed.putString("changePassword", user.getMappModule().changePassword);
            ed.putString("inviteFriends", user.getMappModule().inviteFriends);
            ed.putString("myCollection", user.getMappModule().myCollection);
        }
        ed.commit();
    }
}
